package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
@Api(description = "注册管理")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送邮箱注册验证码
    @ApiOperation(value = "发送邮箱注册验证码")
    @GetMapping("/send/{email}")
    public R sendMsm(@PathVariable String email) throws EmailException {
        /**
         * 1、从redis获取验证码，如果获取到直接返回
         * **/
        String code = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }

        /**
         * 2、如果redis获取不到，进行阿里云发送
         * **/
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        // 设置发送者名称
        param.put("name","谷粒学院");
        // 设置发送主题
        param.put("subject","谷粒学院 用户注册验证码");
        // 设置发送信息
        param.put("msg","<h1>您的验证码是 "+code+
                ",用于用户注册,五分钟之内有效,请您妥善保管请勿泄露【谷粒学院】</h1>");

        //调用service发送短信的方法
        boolean isSend = msmService.send(param,email);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("邮箱注册验证码发送失败");
        }
    }


}
